<template>
    <div class="upload">
        <template v-if="imgUrl.length">
            <div v-for="(item, index) in imgUrl" class="item" :style="{ border: item ? 'none' : '1px solid #bfbfbf' }">
                <img :src="item.url" class="img" />
                <div class="delete" @click.stop="deleteImg(index)">x</div>
            </div>
        </template>
        <el-upload :show-file-list="false" action="" :http-request="upLoadRequest" ref="uploadRef">
            <div class="upload-img">
                <el-icon :size="50" color="#979797">
                    <Plus />
                </el-icon>
            </div>
        </el-upload>
    </div>
</template>

<script setup>
import { Plus } from "@element-plus/icons-vue";
import { upload } from "@/service/api/upload.js";
import { ref, watch } from "vue";
const props = defineProps({
    imgUrl: {
        type: Array,
        default: []
    }
});
const emits = defineEmits(["upload"]);
const form = new FormData();
const uploadRef = ref(null);
const imgUrl = ref([]);
const loading = ref(false);
let id = [];
watch(
    () => props.imgUrl,
    (newImgUrl) => {
        imgUrl.value = newImgUrl;
    },
    { immediate: true }
);
const deleteImg = (index) => {
    imgUrl.value.splice(index, 1);
    emits("upload", imgUrl.value);
};
const upLoadRequest = ({ file }) => {
    loading.value = true;
    form.append("file", file);
    upload(form)
        .then((res) => {
            loading.value = false;
            if (res.code === 200) {
                imgUrl.value.push({ url: URL.createObjectURL(file), id: res.data });
                emits("upload", imgUrl.value);
                uploadRef.value.handleRemove(form.get("file"));
                form.delete("file");
            }
        })
        .catch((err) => {
            loading.value = false;
        });
};
</script>

<style lang="scss" scoped>
.upload {
    display: flex;
    .item {
        box-sizing: border-box;
        position: relative;
        margin-right: 16px;
        width: 120px;
        height: 120px;
        transition: all 0.3s;
        .img {
            width: 100%;
            height: 100%;
            vertical-align: bottom;
        }
    }
    .delete {
        position: absolute;
        top: 5px;
        right: 5px;
        width: 23px;
        height: 23px;
        font-size: 16px;
        color: #fff;
        background-color: rgb(0, 0, 0, 0.2);
        border-radius: 50%;
        text-align: center;
        line-height: 20px;
        cursor: pointer;
    }
    .upload-img {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        width: 120px;
        height: 120px;
        border: 1px solid #bfbfbf;
        .icon {
            font-size: 40px;
            color: #666;
        }
    }
}
</style>
